import React, { Suspense, lazy } from 'react';
import PropTypes from 'prop-types';

/**
 * 动态导入组件
 * @param {string} componentPath - 组件路径
 * @param {ReactNode} fallback - 加载中的UI
 */
const AsyncComponent = ({ componentPath, fallback = <div>Loading...</div> }) => {
  const LazyComponent = lazy(() => import(`../../${componentPath}`));
  
  return (
    <Suspense fallback={fallback}>
      <LazyComponent />
    </Suspense>
  );
};

AsyncComponent.propTypes = {
  componentPath: PropTypes.string.isRequired,
  fallback: PropTypes.node,
};

/**
 * 动态加载路由组件
 * @param {Object} routesConfig - 路由配置
 * @returns {JSX.Element} 路由组件
 */
const createLazyRoutes = (routesConfig) => {
  return routesConfig.map((route) => ({
    ...route,
    component: lazy(() => import(`../../pages/${route.componentPath}`)),
    exact: route.exact || false,
  }));
};

/**
 * 预加载组件
 * @param {string} componentPath - 组件路径
 */
const preloadComponent = (componentPath) => {
  const component = import(`../../${componentPath}`);
  return component;
};

export { AsyncComponent, createLazyRoutes, preloadComponent };
